/**  
 * 
 * @Title:  UserScoreTask.java   
 * @Package com.bicon.datamanager.task   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: 123774135@qq.com     
 * @date:   2018年7月24日 下午4:28:52   
 * @version V1.0 
 * @Copyright: 2018 www.tydic.com Inc. All rights reserved. 
 * 
 */  
package com.bicon.base.data.service.quartz.task;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.IOUtils;
import org.codehaus.jackson.type.TypeReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;
import com.bicon.base.data.common.StringTools;
import com.bicon.base.data.common.UUIDGenerator;
import com.bicon.base.data.common.exception.BusinessException;
import com.bicon.base.data.common.filter.FilterUtil;
import com.bicon.base.data.common.tools.DateUtil;
import com.bicon.base.data.common.tools.DoubleUtils;
import com.bicon.base.data.common.tools.JsonUtil;
import com.bicon.base.data.face.UserScoreFace;
import com.bicon.base.data.pojo.botu.TAUser;
import com.bicon.base.data.pojo.botu.THUserDietDetail;
import com.bicon.base.data.pojo.botu.THUserDrug;
import com.bicon.base.data.pojo.botu.THUserHealthDataDetail;
import com.bicon.base.data.pojo.botu.THUserSleep;
import com.bicon.base.data.pojo.botu.THUserSportRecord;
import com.bicon.base.data.util.Constants;
import com.bicon.base.data.util.DictionaryCode;
import com.bicon.base.data.util.IndexUtil;
import com.bicon.base.data.util.PairVo;
import com.bicon.base.data.util.PersonSocreEntity;
import com.bicon.base.data.util.PrarmsVo;
import com.bicon.base.data.util.UserpercentModel;
import com.google.common.base.Predicate;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;


/**   
 * @ClassName:  UserScoreTask   
 * @Description:用户评分定时任务   
 * @author: 123774135@qq.com 
 * @date:   2018年7月24日 下午4:28:52   
 *     
 * @Copyright: 2018 
 * 
 */
@Component("userScoreTask")
public class UserScoreTask {

	
	private Logger logger =LoggerFactory.getLogger(this.getClass());
	@Autowired
	private UserScoreFace userScoreFace;

	private static final String SPROT_JSON_PATH = "sport_prarms.json";
	
	private static final double STAND_VALUE = 100;
	
	public static final Map<String,String> map = Constants.VALUE_MAP;
	
	
	public void userscoreTask() throws IOException {
		logger.info("开始定时任务,当前时间:{}",DateUtil.now(DateUtil.format4));
		Map<String,String> map = Maps.newHashMap();
		List<UserpercentModel> userList = Lists.newArrayList();
		 try {
			 logger.info("开始获取运动参数文件，文件名称为:{}",SPROT_JSON_PATH);
			 InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(SPROT_JSON_PATH);
			 String json_str = IOUtils.toString(inputStream, "utf-8");
			 List<PrarmsVo> sports = (List<PrarmsVo>)JsonUtil.jsonNodetoObject(JsonUtil.getNode(json_str, "prarms"), new TypeReference<List<PrarmsVo>>() {});
			 for(PrarmsVo m1 : sports) {
				
				map.put(m1.getName(), m1.getValue());
				
			 }
			 logger.info("结束获取运动参数文件，文件名称为:{}",SPROT_JSON_PATH);
			 List<TAUser> tausers = userScoreFace.getUserService().findTAUser();
			 List<TAUser> list = FilterUtil.filterValues(tausers, new Predicate<TAUser>() {

					@Override
					public boolean apply(TAUser input) {
						
						return !StringTools.isBlank(input.getBirthday()) && !StringTools.isBlank(String.valueOf(input.getGender()));
					}
					
			});
				//
	            if(!list.isEmpty()) {
	            	
	    		  for(int i = 0;i<list.size();i++) {
	    			PersonSocreEntity personSocreEntity = new PersonSocreEntity();
	    			TAUser tauser = list.get(i);
//	    			if(null == tauser) {
//	    				continue;
//	    			}
	    			String userid = tauser.getId();
	    			if("4f1df2fbccb44464b579cc602fb3b2be".equals(userid)) {
	    				System.out.println(userid);
	    			}
	    			String sex = 1 == tauser.getGender() ?"男":"女";
	    			personSocreEntity.userid = userid;
	    			personSocreEntity.sex = sex;
	    			
	    			//String code = tauser.getDictionary_code();
	    			String age = String.valueOf(DateUtil.getyearIntevalYears(DateUtil.now(DateUtil.format2), tauser.getBirthday(),DateUtil.format2));
	    			personSocreEntity.age = age;
	    			UserBaseEntity userbaseentity = new UserBaseEntity(userid,age,sex);
	    			//获取每个用户的健康信息
	    			List<THUserHealthDataDetail> listHealthDataDetail  = userScoreFace.getThuserHealthDataDetailService().findTHUserHealthDataDetailByUid(tauser.getId());
	    			this.builderUserBaseEntity(userbaseentity, listHealthDataDetail,tauser);
	    			personSocreEntity.height = userbaseentity.height;
					personSocreEntity.weight = userbaseentity.weight;
	    			if(StringTools.isBlank(StringTools.mkString(userbaseentity.height)) || StringTools.isBlank(StringTools.mkString(userbaseentity.weight))) {
	    				continue;//存在bug问题
	    			}
	    			if("null".equals(userbaseentity.height) || "null".equals(userbaseentity.weight)) {
	    				continue;//存在bug问题
	    			}
	    			if("0.0".equals(userbaseentity.height) || "0.0".equals(userbaseentity.weight)) {
	    				continue;//存在bug问题
	    			}
	    			//进行指标计算
//	    			 //bmi指标
	    			 String bmi = IndexUtil.bmiIndex(Double.parseDouble(userbaseentity.height),  Double.parseDouble(userbaseentity.weight));
	    			 personSocreEntity.bmi = bmi;
	    			 //基础健康评分
	    			 String healthscore = IndexUtil.healthscore(Double.parseDouble(userbaseentity.height),  Double.parseDouble(userbaseentity.weight), Double.parseDouble(userbaseentity.age));
	    			 personSocreEntity.healthscore = healthscore;
	    			 logger.info("当前用户编号:{},BMI打分{},基础健康评分:{}",new Object[] {userid,bmi,healthscore});
	    			 //年龄影响
	    			String ageEffect =  IndexUtil.ageEffectOfIndex(Double.parseDouble(age));
	    			 logger.info("当前用户编号:{},年龄影响:{}",new Object[] {userid,ageEffect});
	    			 personSocreEntity.ageEffect = ageEffect;
	    			 //体脂率影响
		    		String bodyfatrate =  IndexUtil.bodyfatrateIndex(Double.parseDouble(userbaseentity.height),  Double.parseDouble(userbaseentity.weight),Double.parseDouble(age),sex);
		    		String bodyfatrateIndexformate = IndexUtil.bodyfatrateIndexformate(Double.parseDouble(userbaseentity.height),  Double.parseDouble(userbaseentity.weight),Double.parseDouble(age),sex);
		    		logger.info("当前用户编号:{},体脂率影响:{}",new Object[] {userid,bodyfatrate});
		    		personSocreEntity.bodyfatrate = bodyfatrate;
		    		 //体脂率影响
		    		//步伐长度
		    		String pacelength = IndexUtil.pacelength(sex, Double.parseDouble(userbaseentity.height));
		    		logger.info("当前用户编号:{},步伐长度:{}",new Object[] {userid,pacelength});
		    		personSocreEntity.pacelength = pacelength;
	    			//获得饮食记录THUserDietDetail,计算食物卡路里之和
		    		double sum_food_weigth_zc = sumOffoodweight(userid,DictionaryCode.LRTZ_YSRL_ZC.name());//早餐
		    		double sum_food_weigth_wc = sumOffoodweight(userid,DictionaryCode.LRTZ_YSRL_WC.name());//午餐
		    		double sum_food_weigth_wc1 = sumOffoodweight(userid,DictionaryCode.LRTZ_YSRL_WC1.name());//晚餐
		    		 logger.info("当前用户编号:{},食物卡路里之和{}",new Object[] {userid,sum_food_weigth_zc});
		    		 double totle_food = sum_food_weigth_zc + sum_food_weigth_zc+ sum_food_weigth_wc1;
		    		 personSocreEntity.sum_food_weigth = String.valueOf(totle_food);
//	    			 //饮食记录评分,food系数分为早餐系数，午餐系数,晚餐系统，
	    			 String foodratio_zc = IndexUtil.foodratio(sum_food_weigth_zc, Double.parseDouble(userbaseentity.height), Double.parseDouble(userbaseentity.weight), Double.parseDouble(userbaseentity.age), sex,DictionaryCode.LRTZ_YSRL_ZC.name());
	    			 logger.info("当前用户编号:{},早餐系数{}",new Object[] {userid,foodratio_zc});
	    			 String foodratio_wc = IndexUtil.foodratio(sum_food_weigth_wc, Double.parseDouble(userbaseentity.height), Double.parseDouble(userbaseentity.weight), Double.parseDouble(userbaseentity.age), sex,DictionaryCode.LRTZ_YSRL_WC.name());
	    			 logger.info("当前用户编号:{},午餐系{}",new Object[] {userid,foodratio_wc});
	    			 String foodratio_wc1 = IndexUtil.foodratio(sum_food_weigth_wc1, Double.parseDouble(userbaseentity.height), Double.parseDouble(userbaseentity.weight), Double.parseDouble(userbaseentity.age), sex,DictionaryCode.LRTZ_YSRL_WC1.name());
	    			 logger.info("当前用户编号:{},晚餐系统{}",new Object[] {userid,foodratio_wc1});
	    			 //运动评分，先计算卡里路
	    			 double sportcalorie = sportcalorie(userid,userbaseentity,map,listHealthDataDetail);
	    			 logger.info("当前用户编号:{},获得运动评分，先计算卡里路{}",new Object[] {userid,sportcalorie});
	    			 personSocreEntity.sportcalorie = String.valueOf(sportcalorie);
	    			 //bmr基础代谢
	    			 String basicmetabolicrate = IndexUtil.basicmetabolicrate(Double.parseDouble(userbaseentity.height), Double.parseDouble(userbaseentity.weight), Double.parseDouble(userbaseentity.age), sex);
	    			 logger.info("当前用户编号:{},基础代谢{}",new Object[] {userid,basicmetabolicrate});
	    			 personSocreEntity.basicmetabolicrate = basicmetabolicrate;
	    			 //理想体重
	    			 String idealweight = IndexUtil.idealweight(Double.parseDouble(userbaseentity.height));
	    			 logger.info("当前用户编号:{},理想体重{}",new Object[] {userid,idealweight});
	    			 personSocreEntity.idealweight = idealweight;
	    			 //理想BMR
	    			 String idealBmr = IndexUtil.idealBmr(Double.parseDouble(userbaseentity.height), Double.parseDouble(userbaseentity.weight), Double.parseDouble(userbaseentity.age), sex);
	    			 logger.info("当前用户编号:{},理想BMR{}",new Object[] {userid,idealBmr});
	    			 personSocreEntity.idealBmr = idealBmr;
	    			 //维持现有状况摄入卡路里
	    			 String maintaincurrentsituationcalorieintake = IndexUtil.maintaincurrentsituationcalorieintake(Double.parseDouble(basicmetabolicrate), sportcalorie);
	    			 logger.info("当前用户编号:{},维持现有状况摄入卡路里{}",new Object[] {userid,maintaincurrentsituationcalorieintake});
	    			 personSocreEntity.maintaincurrentsituationcalorieintake = maintaincurrentsituationcalorieintake;
	    			 //理想摄入卡洛里
	    		     String ideacalorieintake = IndexUtil.ideacalorieintake(Double.parseDouble(idealBmr), sportcalorie);
	    		     logger.info("当前用户编号:{},理想摄入卡洛里{}",new Object[] {userid,ideacalorieintake});
	    		     personSocreEntity.ideacalorieintake = ideacalorieintake;
	    		     //食物评分，分为早餐评分，午餐评分，晚餐评分
	    		     String foodSocre_zc =  IndexUtil.foodSocre(Double.parseDouble(foodratio_zc));//早餐评分
	    		     logger.info("当前用户编号:{},早餐评分{}",new Object[] {userid,foodSocre_zc});
	    		     String foodSocre_wc =  IndexUtil.foodSocre(Double.parseDouble(foodratio_wc));//早餐评分
	    		     logger.info("当前用户编号:{},午餐评分{}",new Object[] {userid,foodSocre_wc});
	    		     String foodSocre_wc1 =  IndexUtil.foodSocre(Double.parseDouble(foodratio_wc1));//早餐评分
	    		     logger.info("当前用户编号:{},晚餐评分{}",new Object[] {userid,foodSocre_wc1});
	    		     String foodSocreoftotal = IndexUtil.foodSocreoftotal(Double.parseDouble(foodSocre_zc), Double.parseDouble(foodSocre_wc1), Double.parseDouble(foodSocre_wc));
	    		     logger.info("当前用户编号:{},食物评分{}",new Object[] {userid,foodSocreoftotal});
	    		     personSocreEntity.foodSocre = foodSocreoftotal;
	    		     //运动评分
	    		     String sportscore = IndexUtil.sportscore(sportcalorie,Double.parseDouble(basicmetabolicrate),Double.parseDouble(idealBmr));
	    		     logger.info("当前用户编号:{},运动评分{}",new Object[] {userid,sportscore});
	    		     personSocreEntity.sportscore = sportscore;
	    			 //血压打分（低压）
	    			 //需要打分,分为高压和低压打分
	    			 //低压
	    			 //List<THUserHealthDataDetail> lowpressures  =   FilterUtil.filterValues(listHealthDataDetail, new UserHealthDataDetailFilter(DictionaryCode.LRTZ_JKZB_XY_SZY.name()));
		    			double lowpressure = 0;
//		    			if(!lowpressures.isEmpty()) {
//		    				lowpressure = Double.parseDouble(lowpressures.get(0).getIndexValue());
//		    			}
		    			double point_lowpresssure =Double.parseDouble(IndexUtil.influenceOfbloodpressureforlowpressure(lowpressure));
	    			  //计算高压
		    			//List<THUserHealthDataDetail> heightpressures  =   FilterUtil.filterValues(listHealthDataDetail, new UserHealthDataDetailFilter(DictionaryCode.LRTZ_JKZB_XY_SSY.name()));
		    			double heightpressure = 0;
//		    			if(!heightpressures.isEmpty()) {
//		    				heightpressure = Double.parseDouble(heightpressures.get(0).getIndexValue());
//		    			}
		    			double point_heightpressure =Double.parseDouble(IndexUtil.influenceOfbloodpressureforlowpressure(heightpressure));
		    			double total_press = point_heightpressure + point_lowpresssure;
		    			logger.info("当前用户编号:{},获得血压（高/低）{}",new Object[] {userid,total_press});
		    			personSocreEntity.total_press = String.valueOf(total_press);
	    			//计算睡眠
	    			 String sleepTimescore = null;
	    			 List<THUserSleep> sleepRecords = this.getTHUserSleepRecord(userid);
	    			 List<PairVo<String,String>> sleepList = Lists.newArrayList();
	    			 
	    			 if(!sleepRecords.isEmpty()) {
	    				 PairVo<String,String> sleepPairVo = new PairVo<String,String>(sleepRecords.get(0).getStartTime(),sleepRecords.get(0).getEndTime());
	    				 //获取入睡时间评分
	    				  sleepTimescore = IndexUtil.sleepTimescore(sleepPairVo,DateUtil.format1);
	    				  sleepList.add(sleepPairVo);
	    			 }
	    			 String sleepduration = IndexUtil.sleepduration(sleepList, DateUtil.format1);//睡眠时长
	    			 String ideasleepduration = IndexUtil.demandsleeptime(Double.parseDouble(age));//理想睡眠
	    			 String sleepdurationscore = IndexUtil.sleepdurationScore(Double.parseDouble(sleepduration), Double.parseDouble(ideasleepduration));//睡眠时长评分
	    			 //计算睡眠评分double sleepTimescore, String date, double age, double sleepduration
	    			 String beforday = DateUtil.getStringDate(DateUtil.getADayBefore(new Date(),1), DateUtil.format1);
	    			 String sleepScore = IndexUtil.sleepScore(StringTools.isBlank(sleepTimescore)?0:Double.parseDouble(sleepTimescore),beforday,Double.parseDouble(age),StringTools.isBlank(sleepdurationscore)?0:Double.parseDouble(sleepdurationscore));
	    			 logger.info("当前用户编号:{},睡眠评分{}",new Object[] {userid,sleepScore});
	    			 personSocreEntity.sleepScore = sleepScore;
	    			 //计算体温打分
	    			 //List<THUserHealthDataDetail> temperaturescores  =   FilterUtil.filterValues(listHealthDataDetail, new UserHealthDataDetailFilter(DictionaryCode.LRTZ_JKZB_TW.name()));
	    			 //会存在多个，当前就拿最后一个
	    			 double temperature_value = 0;
//	    			 if(!temperaturescores.isEmpty()) {
//	    				  String temperature = temperaturescores.get(0).getIndexValue();
//	    				  temperature_value = Double.parseDouble(IndexUtil.temperaturescore(Double.parseDouble(temperature)));
//	    			 }
	    			 //logger.info("当前用户编号:{},体温评分{}",new Object[] {userid,temperature_value});
	    			 personSocreEntity.temperature_value = String.valueOf(temperature_value);
	    			 //心率打分
	    			 List<THUserHealthDataDetail> heartrates  =   FilterUtil.filterValues(listHealthDataDetail, new UserHealthDataDetailFilter(DictionaryCode.LRTZ_JKZB_XL.name()));
	    			 double heartrate_value = 0;
	    			 if(!heartrates.isEmpty()) {
	    				 String heartratesvalue = heartrates.get(0).getIndexValue();
	    				 heartrate_value = Double.parseDouble(IndexUtil.heartrate(Double.parseDouble(heartratesvalue))); 
	    			 }
	    			 logger.info("当前用户编号:{},心率温评分{}",new Object[] {userid,heartrate_value});
	    			 personSocreEntity.heartratevalue = String.valueOf(heartrate_value);
	    			 //血糖打分，需要餐前和餐后的的两个打分
	    			// List<THUserHealthDataDetail> bloodpressureImpactaftrefoods  =   FilterUtil.filterValues(listHealthDataDetail, new UserHealthDataDetailFilter(DictionaryCode.LRTZ_JKZB_XT_FH.name()));
	    			 double booldafter_value = 0;
//	    			 if(!bloodpressureImpactaftrefoods.isEmpty()) {
//	    				 String booldaftervalue = bloodpressureImpactaftrefoods.get(0).getIndexValue();
//	    				 booldafter_value = Double.parseDouble(IndexUtil.bloodpressureImpactaftrefood(Double.parseDouble(booldaftervalue))); 
//	    			 }
//	    			 logger.info("当前用户编号:{},饭后血糖评分{}",new Object[] {userid,booldafter_value});
	    			 personSocreEntity.booldafter_value = String.valueOf(booldafter_value);
	    			 //饭前
	    			// List<THUserHealthDataDetail> bloodpressureImpacts  =   FilterUtil.filterValues(listHealthDataDetail, new UserHealthDataDetailFilter(DictionaryCode.LRTZ_JKZB_XT_FQ.name()));
	    			 double booldbefor_value = 0;
//	    			 if(!bloodpressureImpacts.isEmpty()) {
//	    				 String booldbeforvalue = bloodpressureImpacts.get(0).getIndexValue();
//	    				 booldbefor_value = Double.parseDouble(IndexUtil.bloodpressureImpactaftrefood(Double.parseDouble(booldbeforvalue))); 
//	    			 }
//	    			 logger.info("当前用户编号:{},饭前血糖评分{}",new Object[] {userid,booldbefor_value});
	    			 personSocreEntity.booldbefor_value = String.valueOf(booldbefor_value);
	    			 //综合血糖记录
	    			 double total_bloodpressure = booldafter_value + booldbefor_value;
	    			 logger.info("当前用户编号:{},血糖总评分{}",new Object[] {userid,total_bloodpressure});
	    			 personSocreEntity.total_bloodpressure = String.valueOf(total_bloodpressure);
	    			 //用药评分
	    			 double drugsscore = 0;
//	    			 List<THUserDrug> userDrugs = this.getTHUserDrugRecord(userid);
//	    			 if(!userDrugs.isEmpty()) {
//	    				 //计算用药间隔时长
//	    				for(THUserDrug userDrug : userDrugs) {
//	    					
//	    				} 
//	    			 }
	    			 personSocreEntity.drugsscore = String.valueOf(drugsscore);
	    			//标准饮食卡路里
			    	String  standard_diet = new DecimalFormat("0.00").format(Double.parseDouble(basicmetabolicrate)*1.1);
			    	logger.info("当前用户编号:{},标准饮食卡路里{}",new Object[] {userid,standard_diet});
			    	 personSocreEntity.standard_diet = standard_diet;
	    			//日初步评分
		    		String dailypreliminaryscore = IndexUtil.dailypreliminaryscore(Double.parseDouble(foodSocreoftotal), Double.parseDouble(sportscore), total_bloodpressure, booldafter_value, heartrate_value, temperature_value, Double.parseDouble(sleepScore), 0);	
		    		logger.info("当前用户编号:{},日初步评分{}",new Object[] {userid,dailypreliminaryscore});
		    		personSocreEntity.dailypreliminaryscore = dailypreliminaryscore;
		    		 //还要计算修正值
		    		double modify_diet =  Double.parseDouble(IndexUtil.modifyFunction(Double.parseDouble(dailypreliminaryscore), STAND_VALUE, Double.parseDouble(foodSocreoftotal)));//饮食修正值
		    		double modify_boold =  Double.parseDouble(IndexUtil.modifyFunction(Double.parseDouble(dailypreliminaryscore), STAND_VALUE, booldafter_value));//血糖修正值
		    		double modify_heigthpress =  Double.parseDouble(IndexUtil.modifyFunction(Double.parseDouble(dailypreliminaryscore), STAND_VALUE, heightpressure));//高压修正值
		    		double modify_lowpress =  Double.parseDouble(IndexUtil.modifyFunction(Double.parseDouble(dailypreliminaryscore), STAND_VALUE, lowpressure));//低压压修正值
		    		double modify_heartratio =  Double.parseDouble(IndexUtil.modifyFunction(Double.parseDouble(dailypreliminaryscore), STAND_VALUE, heartrate_value));//心率修正值
		    		double modify_temperature =  Double.parseDouble(IndexUtil.modifyFunction(Double.parseDouble(dailypreliminaryscore), STAND_VALUE, temperature_value));//体温修正值
		    		double modify_sleep =  Double.parseDouble(IndexUtil.modifyFunction(Double.parseDouble(dailypreliminaryscore), STAND_VALUE, Double.parseDouble(sleepScore)));//体温修正值
		    		double modify_drugs = Double.parseDouble(IndexUtil.modifyFunction(Double.parseDouble(dailypreliminaryscore), STAND_VALUE, drugsscore));//体温修正值
		    		//日最终评分
		    		 String dailyendscore = IndexUtil.dailyendscore(Double.parseDouble(dailypreliminaryscore),STAND_VALUE,STAND_VALUE,modify_diet,modify_boold,(modify_heigthpress+modify_lowpress),modify_heartratio,modify_temperature,modify_sleep,modify_drugs);
		    		 personSocreEntity.dailyendscore = dailyendscore;
		    		 logger.info("当前用户编号:{},日最终评分{}",new Object[] {userid,dailyendscore});
		    		//基础评分
		    		 String basicscore = IndexUtil.basicscore(Double.parseDouble(userbaseentity.height), Double.parseDouble(userbaseentity.weight), Double.parseDouble(userbaseentity.age));
		    		 logger.info("当前用户编号:{},基础评分{}",new Object[] {userid,basicscore});
		    		 personSocreEntity.basicscore = basicscore;
		    		 //行为评分
		    		 String behavioralscore = IndexUtil.behavioralscore(Double.parseDouble(foodSocreoftotal), Double.parseDouble(sportscore), Double.parseDouble(sleepScore),Double.parseDouble(ageEffect),Double.parseDouble(basicscore));
		    		 logger.info("当前用户编号:{},行为评分{}",new Object[] {userid,behavioralscore});
		    		 personSocreEntity.behavioralscore = behavioralscore;
		    		 //总的评分
		    		 String socre = IndexUtil.score(Double.parseDouble(basicscore),Double.parseDouble(behavioralscore));
		    		 logger.info("当前用户编号:{},总的评分{}",new Object[] {userid,socre});
		    		 personSocreEntity.socre = socre;
		    		 personSocreEntity.bmilevel = builderBmiLevel(Double.parseDouble(bmi));
		    		 personSocreEntity.bodyfatlevel = builderbodyfatrateLevel(Double.parseDouble(bodyfatrateIndexformate) /100,sex);
		    		 personSocreEntity.healthlevel = builderhealthlevel(Double.parseDouble(socre));
		    		 personSocreEntity.datetime = DateUtil.getStringDate(DateUtil.getADayBefore(new Date(),1), DateUtil.format1);
		    		 personSocreEntity.date = DateUtil.getStringDate(DateUtil.getADayBefore(new Date(),1), DateUtil.format2);
		    		 personSocreEntity.id= new UUIDGenerator().generate().toString();
		    		 //进行入库操作mongodb
		    		 //根据id查询当前是否存在该记录，如果存在，不在进行插入操作
		    		
		    		 saveUserScore(personSocreEntity);
		    		 userList.add(new UserpercentModel(personSocreEntity.socre, personSocreEntity.userid));
		    		 
	    		  }
	            }
	          //计算百分比
	    		 saveUserpercent(userList);
		 }catch(BusinessException ex) {
			 ex.printStackTrace();
				logger.info("系统发生错误,错误原因:{}",ex.getMsg());
		 }
		logger.info("结束定时任务,当前时间:{}",DateUtil.now(DateUtil.format4));
	}
	
	/**
	 * 
	 * @Title: saveUserScore   
	 * @Description:存入mongodb   
	 * @param personSocreEntity      
	 * void      
	 * @throws
	 */
	private void saveUserScore(PersonSocreEntity personSocreEntity) {
		//根据ID和日期进行查询是否存在
		
		 Query query = new Query();
		 query.addCriteria(Criteria.where("userid").is(personSocreEntity.userid).and("date").is(personSocreEntity.date));
		 long count = userScoreFace.getMongoTemplate().count(query, "personal_health_score");
		 if(count == 0) {
			 userScoreFace.getMongoTemplate().insert(personSocreEntity);
		 }else {
			 logger.info("已经存在当前的用户评分信息,进行更新操作");
			 //进行更新
			 Update update = new Update();
			 update.set("healthscore", personSocreEntity.healthscore);
			 update.set("sex", personSocreEntity.sex);
			 update.set("ageEffect", personSocreEntity.ageEffect);
			 update.set("bodyfatrate", personSocreEntity.bodyfatrate);
			 update.set("bmi", personSocreEntity.bmi);
			 update.set("pacelength", personSocreEntity.pacelength);
			 update.set("sum_food_weigth",personSocreEntity.sum_food_weigth);
			 //update.set("foodratio", personSocreEntity.foodratio);
			 update.set("basicmetabolicrate", personSocreEntity.basicmetabolicrate);
			 update.set("idealweight", personSocreEntity.idealweight);
			 update.set("maintaincurrentsituationcalorieintake",personSocreEntity.maintaincurrentsituationcalorieintake);
			 update.set("ideacalorieintake", personSocreEntity.ideacalorieintake);
			 update.set("foodSocre", personSocreEntity.foodSocre);
			 update.set("sportscore", personSocreEntity.sportscore);
			 update.set("total_press", personSocreEntity.total_press);
			 update.set("sleepScore", personSocreEntity.sleepScore);
			 update.set("temperature_value", personSocreEntity.temperature_value);
			 update.set("booldafter_value", personSocreEntity.booldafter_value);
			 update.set("booldbefor_value", personSocreEntity.booldbefor_value);
			 update.set("total_bloodpressure", personSocreEntity.total_bloodpressure);
			 update.set("standard_diet", personSocreEntity.standard_diet);
			 update.set("dailypreliminaryscore", personSocreEntity.dailypreliminaryscore);
			 update.set("basicscore", personSocreEntity.basicscore);
			 update.set("behavioralscore", personSocreEntity.behavioralscore);
			 update.set("dailyendscore", personSocreEntity.dailyendscore);
			 update.set("bmilevel", personSocreEntity.bmilevel);
			 update.set("socre", personSocreEntity.socre);
			 update.set("bodyfatlevel", personSocreEntity.bodyfatlevel);
			 update.set("healthlevel", personSocreEntity.healthlevel);
			 update.set("datetime", DateUtil.getStringDate(DateUtil.getADayBefore(new Date(),1), DateUtil.format1));
			 userScoreFace.getMongoTemplate().updateMulti(query, update, PersonSocreEntity.class);
			
		 }
	}
	
	private void saveUserpercent(List<UserpercentModel> userList) {
		if(!userList.isEmpty()) {
			
			int size = userList.size();
			for(UserpercentModel u : userList) {
				List<UserpercentModel> list = FilterUtil.filterValues(userList, new Predicate<UserpercentModel>() {

					@Override
					public boolean apply(UserpercentModel input) {
						String score = u.getScore();
						String inputscore = input.getScore();
						if(Double.parseDouble(inputscore) < Double.parseDouble(score)) {
							return true;
						}
						return false;
					}
					
				});
				//计算占比
				double result = (double)list.size() / (double)size;
				String str_result = DoubleUtils.parseDecimalFormatStr(result, "0.00");
				u.setPercent(str_result);
				u.setDate(DateUtil.getStringDate(DateUtil.getADayBefore(new Date(),1), DateUtil.format2));
				//再次进行更新操作
				Query query = new Query();
				
				query.addCriteria(Criteria.where("userid").is(u.getUserid()).and("date").is(u.getDate()));
				long count = userScoreFace.getMongoTemplate().count(query, "personal_health_score");
				//System.out.println("count:"+count);
				if(count > 0) {
					Update update = new Update();
					update.set("percent", str_result);
					userScoreFace.getMongoTemplate().upsert(query, update, "personal_health_score");
				}
				
				
				
			}
			
		}
		 
	}

	
		
	/**
	 * 
	 * @Title: sportpoint   
	 * @Description: 运动评分   
	 * @param userid
	 * @param userbaseentity
	 * @param map
	 * @param listHealthDataDetail
	 * @return      
	 * double      
	 * @throws
	 */
	private double sportcalorie(String userid,UserBaseEntity userbaseentity,Map<String,String>  map,List<THUserHealthDataDetail> listHealthDataDetail) {
		//获取运动记录
		 List<THUserSportRecord> userSportRecords = userScoreFace.getThuserSportRecordService().findTHUserSportRecordByuid(userid);
		 String ratio = null;
		 double sum_calorie = 0;
		 if(!userSportRecords.isEmpty()) {
			 
			 for(THUserSportRecord thusersportrecord : userSportRecords) {
				 String sprotname = thusersportrecord.getName();//运动名称
				 String longtime = thusersportrecord.getLongTime();//运动时长
				 //String energyvalue = thusersportrecord.getEnergyValue();//运动能量
				 //计算卡路里之和
				  ratio = StringTools.mkString(map.get(sprotname));//会有找不到对应的系数的可能性
				 if(StringTools.isBlank(ratio)) {
					 logger.info("当前参数表里面不存在{}对应的系数值",sprotname);
				 }else {
					 String sportforcalorie = IndexUtil.sportforcalorie(ratio,Double.parseDouble(userbaseentity.weight),Integer.parseInt(longtime));
					 sum_calorie = sum_calorie + Double.parseDouble(sportforcalorie); 
				 }
				 
			 }
		 }
		 //计算计步器模块
		 //1 计算步伐长度
		  List<THUserHealthDataDetail> pacel_list =  FilterUtil.filterValues(listHealthDataDetail, new UserHealthDataDetailFilter(DictionaryCode.LRTZ_JKZB_STEP.name()));
		  int numberOfpacel = 0;//走的总步数
		  if(!pacel_list.isEmpty()) {
			  for(THUserHealthDataDetail userHealthDataDetail : pacel_list) {
				  numberOfpacel = numberOfpacel + Integer.parseInt(userHealthDataDetail.getIndexValue());
			  }
		  }
		  //2计算步距
		  int pace_casttime =  (int)Double.parseDouble(IndexUtil.casttime(userbaseentity.sex, Double.parseDouble(userbaseentity.height),1.5));//String sex,double height,double ratio 计算步时长
		 //IndexUtil.calorie()
		 //计算步数卡路里,需要计算步时长
		  double  calorie = 0;
		  if(!StringTools.isBlank(ratio)) {
			   calorie = Double.parseDouble(IndexUtil.calorie(Double.parseDouble(userbaseentity.height),pace_casttime,Double.parseDouble(ratio)));
		  }
		
		double sport_point = sum_calorie + calorie;//运动评分
		return sport_point;
	}
	
	/**
	 * 
	 * @Title: sumOffoodweight   
	 * @Description: 食物的卡路里   
	 * @param userid
	 * @return      
	 * double      
	 * @throws
	 */
	private double sumOffoodweight(String userid,String key) {
		 List<THUserDietDetail>  thuserDietDetailRecords = this.getTHUserDietDetailRecords(userid);
		 List<THUserDietDetail> filter_list = FilterUtil.filterValues(thuserDietDetailRecords, new Predicate<THUserDietDetail>() {

			@Override
			public boolean apply(THUserDietDetail input) {
				
				return StringTools.mkString(input.getDictionary_code()).equals(StringTools.mkString(key));
			}
				
			});
		double sum = 0;
		if(!filter_list.isEmpty()) {
			
			for(THUserDietDetail userDietDetail :thuserDietDetailRecords) {
			 //计算卡路里，需要根据系数进行换算
			String weigth =	userDietDetail.getIndex_value();
			double weigth_value =	StringTools.isNmber(weigth)?Double.parseDouble(weigth):0;
			sum = sum + weigth_value;
			}
		}
		return sum;
	}
	
	
	
	
	private void builderUserBaseEntity(UserBaseEntity userbaseentity,List<THUserHealthDataDetail> listHealthDataDetail,TAUser tauser) {
		String height = null;
		String weight = null;
		if(!listHealthDataDetail.isEmpty()) {
			//获取身高,也许存在多个身高值,拿最后一个根据时间排序查询的倒叙
			
			List<THUserHealthDataDetail> height_list =  FilterUtil.filterValues(listHealthDataDetail, new UserHealthDataDetailFilter(DictionaryCode.LRTZ_JKZB_SG.name()));
			if(!height_list.isEmpty()) {
				 height = StringTools.mkString(height_list.get(0).getIndexValue());
				 userbaseentity.height = height;
			}
			//获取体重
			List<THUserHealthDataDetail> weights =  FilterUtil.filterValues(listHealthDataDetail, new UserHealthDataDetailFilter(DictionaryCode.LRTZ_JKZB_TZ.name()));
			if(!weights.isEmpty()) {
				 weight = StringTools.mkString(weights.get(0).getIndexValue());
				 userbaseentity.weight = weight;
			}
			 logger.info("当前用户编号:{},身高:{},体重:{},年龄:{},性别{}",new Object[] {userbaseentity.userid,userbaseentity.height,userbaseentity.weight,userbaseentity.age,userbaseentity.sex});

    	  
          }else {
        	  //在哪个详情列表里面没有的话，就从用户详情里面获取体重和升高
        	  userbaseentity.height = String.valueOf(tauser.getHeight());
        	  userbaseentity.weight = String.valueOf(tauser.getWeight());
        	  
          }
		//为了防止漏单 
		if(StringTools.isBlank(userbaseentity.height)) {
			 userbaseentity.height = String.valueOf(tauser.getHeight());
		}
		if(StringTools.isBlank(userbaseentity.weight)) {
			userbaseentity.weight = String.valueOf(tauser.getWeight());
		}
	}
	
	private List<THUserDietDetail> getTHUserDietDetailRecords(String uid){
		return userScoreFace.getThuserDietDetailService().findTHUserDietDetailByuid(uid);
	}
	
	private List<THUserSleep> getTHUserSleepRecord(String uid){
		
		return userScoreFace.getThuserSleepService().findTHUserSleepsByUid(uid);
	}
	
    private List<THUserDrug> getTHUserDrugRecord(String uid){
		
		return userScoreFace.getThuserDrugService().findTHUserDrugByUid(uid);
	}
	
	private static class UserHealthDataDetailFilter implements Predicate<THUserHealthDataDetail>{

		public String code;
		
		public UserHealthDataDetailFilter(String code) {
			this.code =  code;
		}
		
		@Override
		public boolean apply(THUserHealthDataDetail arg0) {
			
			return code.equals(arg0.getDictionaryCode());
		}
		
	}
	
	/**
	 * 
	 * @Title: builderBmiLevel   
	 * @Description: bmi等级  
	 * @param bmi
	 * @return      
	 * String      
	 * @throws
	 */
	private String builderBmiLevel(double bmi) {
		String result = "";
		if(bmi < 18.5) {
			result = "偏瘦";
		}else if( bmi >= 18.5  && bmi < 24) {
			result = "健康";
		}else if( bmi >= 24  && bmi < 28) {
			result = "超重";
		}else if( bmi >= 28  && bmi < 30) {
			result = "肥胖";
		}else {
			result = "重度肥胖";
		}
		return result;
	}
	
	/**
	 * 
	 * @Title: builderBmiLevel   
	 * @Description: bmi等级  
	 * @param bmi
	 * @return      
	 * String      
	 * @throws
	 */
	private String builderbodyfatrateLevel(double bodyfat,String sex) {
		String result = "";
		if("男".equals(sex)) {
			if(bodyfat < 11) {
				result = "瘦";
			}else if( bodyfat >= 11  && bodyfat < 16) {
				result = "偏瘦";
			}else if( bodyfat >= 16  && bodyfat < 21) {
				result = "标准";
			}else if( bodyfat >= 21  && bodyfat < 26) {
				result = "肥胖";
			}else {
				result = "重度肥胖";
			}
		}else {
			if(bodyfat < 21) {
				result = "瘦";
			}else if( bodyfat >= 21  && bodyfat < 26) {
				result = "偏瘦";
			}else if( bodyfat >= 26  && bodyfat < 31) {
				result = "标准";
			}else if( bodyfat >= 31  && bodyfat < 36) {
				result = "肥胖";
			}else {
				result = "重度肥胖";
			}
		}
		
		return result;
	}
	
	private String builderhealthlevel(double health) {
		String result = "";
		if( health >= 90  && health <= 100) {
			result = "极佳";
		}else if( health >= 80  && health < 90) {
			result = "良好";
		}else if( health >= 70  && health < 80) {
			result = "一般";
		}else if( health >= 65  && health < 70) {
			result = "较差";
		}
		else if( health >= 60  && health < 65){
			result = "差";
		}
		return result;
	}
	
	private static class UserBaseEntity implements java.io.Serializable{

		/**   
		 * @Fields serialVersionUID : TODO(用一句话描述这个变量表示什么)   
		 */ 
		private static final long serialVersionUID = 8433002207370815244L;
		
		private String userid;
		
		private String height;
		
		private String weight;
		
		private String age;
		
		private String sex;
		
		
        public UserBaseEntity(String userid,String age,String sex) {
			this.userid = userid;
			
			this.age = age;
			this.sex = sex;
		}

		
		
	}
	
	
//	public static void main(String[] args) throws IOException {
//		 InputStream inputStream = new FileInputStream("D:\\eclipse-workspace\\botu-basedata\\botu-basedata\\botu-basedata-admin\\src\\main\\resources\\sport_prarms.json");
//		 String json_str = IOUtils.toString(inputStream, "utf-8");
//		List< Map<String,String>> maps = (List<Map<String, String>>)JsonUtil.jsonNodetoObject(JsonUtil.getNode(json_str, "prarms"), new TypeReference<List<Map<String,String>>>() {
//		});
//		
//	}
}
